<template>
  <BasicTable @register="registerTable">
    <template #headerTop>
      <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
        <template #message>
          <div>
            <span>已选中{{ checkedKeys.length }}条记录</span>
            <div style="position: absolute; top: 4px; right: 10px">
              <Tooltip title="删除">
                <a-button type="text" @click="handleSelectedDelete">
                  <Icon :icon="ICON.DELETE" color="#0960bd" />
                </a-button>
              </Tooltip>
            </div>
          </div>
        </template>
      </Alert>
    </template>
    <template #toolbar>
      <Dropdown
        :trigger="['click']"
        :dropMenuList="[
          {
            text: '创建新的部件包',
            icon: ICON.ADDENTITY,
            event: '',
            onClick: () => {
              openAddModal(true, { key: 'add' });
            },
          },
        ]"
      >
        <a-button type="primary">添加部件包</a-button>
      </Dropdown>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <TableAction
          :actions="[
            {
              icon: ICON.EDIT,
              tooltip: {
                title: '编辑',
                placement: 'top',
              },
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: ICON.CHECK,
              tooltip: {
                title: '详情',
                placement: 'top',
              },
              onClick: handleDetail.bind(null, record),
            },
            {
              icon: ICON.DELETE,
              tooltip: {
                title: '删除',
                placement: 'top',
              },
              disabled: true,
            },
          ]"
          :drop-down-actions="[
            {
              icon: ICON.DOWNLOAD,
              label: '导出部件',
              onClick: handleDownload.bind(null, record),
            },
            {
              icon: ICON.PLUS,
              label: '添加部件',
              onClick: handleAddWidgets.bind(null, record),
            },
          ]"
        />
      </template>
    </template>
  </BasicTable>
  <BasicModal @register="registerDownloadModal" title="导出部件包" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
  <PublicDrawer
    @register="registerDrawer"
    @update-desc-data="handleUpdateDescData"
    :showTabs="['detail', 'version']"
  />
  <AddModal @register="registerAddModal" @success="handleSuccess" />
  <AddWidgetsModal @register="registerAddWidgetModal" @success="handleSuccess" />
</template>

<script setup lang="ts">
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import AddWidgetsModal from './components/AddWidgetsModal.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { Dropdown } from '/@/components/Dropdown';
  import AddModal from './components/AddModal.vue';
  import {
    componentTableSchema,
    searchSchema,
    uploadSchema,
    detailSchema,
  } from './componentTable.data';
  import {
    getCommentTable,
    getBundleWidgetTypesDetails,
    getBundleWidgetTypeFqns,
    exportInfo,
    getWidgetsBundleInfo,
    addWidgetsBundle,
    deleteBundleWidget,
    addWidgetsBundleWidget,
  } from '/@/api/thingsborad/resources/widgets/widgets';
  import { widgetsTableParams } from '/@/api/thingsborad/resources/widgets/widgetsModel';
  import { ICON } from '/@/enums/iconEnum';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { Alert, Tooltip } from 'ant-design-vue';
  import Icon from '/@/components/Icon';
  import { BasicForm, useForm } from '/@/components/Form/';
  import { saveAs } from 'file-saver';
  import { ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useUserStore } from '/@/store/modules/user';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';

  const userStore = useUserStore();
  const downloadId = ref<string>('');
  const info = ref<any>();
  const checkedKeys = ref<any>([]);
  const name = ref<string>('');
  const { createConfirm } = useMessage();
  const [registerTable, { reload, setProps }] = useTable({
    title: '设备',
    columns: componentTableSchema,
    ...tableStyleSetting,
    api: getCommentTable,
    beforeFetch: (value) => {
      let params: widgetsTableParams = {
        page: value.page - 1,
        pageSize: value.pageSize,
        sortProperty: value.field,
        sortOrder: value.order == 'ascend' ? 'ASC' : 'DESC',
        textSearch: value.textSearch,
        tenantOnly: false,
        fullSearch: false,
      };
      return params;
    },
    afterFetch: (res) => {
      let list: any[] = [];
      res.length != 0
        ? res.forEach((item: any) => {
            let tableItem = {
              createdTime: item.createdTime,
              title: item.title,
              system: userStore.getUserInfo.customerId.id == item.tenantId.id,
              id: item.id.id,
            };
            list.push(tableItem);
          })
        : null;
      return list;
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: (record) => ({
        disabled: record.system,
      }),
    },
  });
  const [registerDownloadModal, { openModal: openDownloadModal, closeModal }] = useModal();
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const [registerAddWidgetModal, { openModal: openAddWidgetModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerForm, { validate }] = useForm({
    layout: 'vertical',
    schemas: uploadSchema,
    showActionButtonGroup: false,
  });
  // 编辑
  const handleEdit = (record: Recordable) => {
    openAddModal(true, { key: 'edit', id: record.id });
  };
  // 详情
  const handleDetail = (record: Recordable) => {
    openDrawer(true, {
      entityType: 'WIDGETS_BUNDLE',
      entityId: record.id,
      title: record.title,
      api: getWidgetsBundleInfo,
      detailSchema: detailSchema,
      params: record.id,
    });
  };
  // 抽屉详情数据更改
  const handleUpdateDescData = (value: Recordable) => {
    value.createdTime = value.createdTime;
    value.title = value.title;
    value.image = value.image;
    value.description = value.description;
    value.order = value.order;
  };
  // 导出
  const handleDownload = async (record: Recordable) => {
    downloadId.value = record.id;
    info.value = await exportInfo(downloadId.value);
    name.value = record.title;
    openDownloadModal(true);
  };
  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个部件包吗？`,
      content: '请注意：确认后，所有选定的部件包将被删除，所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteBundleWidget(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };
  // 添加部件
  const handleAddWidgets = (record: Recordable) => {
    openAddWidgetModal(true, { id: record.id });
  };
  const handleSubmit = async () => {
    try {
      const value = await validate();
      let jsValue: any = {
        widgetsBundle: {
          alias: info.value.alias,
          title: info.value.title,
          image: info.value.image,
          description: info.value.description,
          order: info.value.order,
          externalId: info.value.externalId,
          name: info.value.name,
        },
      };
      if (value.isIncluding == 'isIncluding') {
        let params = {
          widgetsBundleId: downloadId.value,
        };
        const value = await getBundleWidgetTypesDetails(params);
        jsValue.widgetTypes = value;
        const jsonBlob = new Blob([JSON.stringify(jsValue)], {
          type: 'application/json',
        });
        saveAs(jsonBlob, `${name.value}.json`);
      } else {
        let params = {
          widgetsBundleId: downloadId.value,
        };
        const value = await getBundleWidgetTypeFqns(params);
        jsValue.widgetTypeFqns = value;
        const jsonBlob = new Blob([JSON.stringify(jsValue)], {
          type: 'application/json',
        });
        saveAs(jsonBlob, `${name.value}.json`);
      }
      closeModal();
    } catch (error) {}
  };

  const handleSuccess = async ({ key, values, image, info }) => {
    if (key == 'add') {
      let params = {
        title: values.title,
        description: values.description,
        image: image,
        order: values.order,
      };
      await addWidgetsBundle(params);
      reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
    } else if (key == 'edit') {
      info.description = values.description;
      info.title = values.title;
      info.image = image;
      info.order = values.order;
      info.name = values.title;
      await addWidgetsBundle(info);
      reload();
    } else if (key == 'addWidgets') {
      await addWidgetsBundleWidget({
        idList: values.widgetIds.widgetIds,
        packageId: values.packageId,
      });
      reload();
    }
  };
</script>
<style lang="less" scoped>
  :deep(.vben-basic-table-form-container .ant-form) {
    padding-left: 0 !important;
    padding-top: 14px !important;
    padding-bottom: 14px !important;
  }
</style>
